package com.simplehc7878.auth.security.jwt;

import com.simplehc7878.auth.common.Result;
import com.simplehc7878.auth.utils.JsonUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.List;

//https://juejin.cn/post/7244089396567982136
@Slf4j
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    private final JwtHelper jwtHelper;
    private final List<String> whiteList;
    private final AntPathMatcher antPathMatcher;

    public JwtAuthTokenFilter(JwtHelper jwtHelper, AntPathMatcher antPathMatcher, List<String> whiteList) {
        this.jwtHelper = jwtHelper;
        this.antPathMatcher = antPathMatcher;
        this.whiteList = whiteList;
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return !CollectionUtils.isEmpty(whiteList)
                && whiteList.stream().anyMatch(path -> antPathMatcher.matchStart(path, request.getRequestURI()));
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws IOException {
        String token = req.getHeader("Authorization");
        try {
            if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
                throw new RuntimeException("token required");
            }
            Claims claims = jwtHelper.getClaims(token.substring(7));
            if (claims == null || !StringUtils.hasText(claims.getSubject())) {
                throw new RuntimeException("invalid token");
            }
            if (new Date().after(claims.getExpiration())) {
                throw new RuntimeException("token expired");
            }
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(
                            claims.getSubject(), null, Collections.emptyList()));
            filterChain.doFilter(req, res);
        } catch (Exception e) {
            log.error("JwtTokenFilter doFilterInternal error, header Authorization:{}", token, e);
            sendUnauthorizedResponse(res, e.getMessage());
        }
    }

    private void sendUnauthorizedResponse(ServletResponse res, String message) throws IOException {
        res.setContentType("application/json");
        res.getWriter().write(JsonUtil.toJson(
                Result.error(
                        HttpStatus.UNAUTHORIZED.value(),
                        HttpStatus.UNAUTHORIZED.getReasonPhrase()+ ":" + message)));
    }
}
